package com.eve.eplus.common.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.Resources;

import com.eve.eplus.common.app.Configuration;
import com.eve.eplus.common.tools.LogTools;
import com.eve.eplus.R;

/**
 * 
 * 第一次时检查数据库。 例如： Thread d = new Thread(new
 * CheckAndTransportDBFile(xxxx,xxx,xxx)); d.start();
 * @author norsie
 * @create 12-12-18
 * **/

public class MoveDBRunnable implements Runnable {
    
	private Context context;

	public MoveDBRunnable(Context context) {
		this.context = context;
	}

	@Override
	public void run() {
		moveDBPos();
	}

	/**
	 * 移动数据库的位置
	 */
	private void moveDBPos() {
		// TODO Auto-generated method stub
		 File dir = new File( Configuration.DATA_PATH );
		if (!dir.exists() || !dir.isDirectory()) {
			dir.mkdir();
		}
		File file = new File(dir, Configuration.DB_NAME);

		if (!file.exists()) {
			FileUtils.loadDbFile(R.raw.eplus_db, file, context.getResources(),
					context.getPackageName());
			try {
				Thread.sleep ( 2000 );
			}
			catch ( InterruptedException e ) {
				e.printStackTrace();
			}
		}
	}


}

class FileUtils {
	 
    public static void loadDbFile(int rawId, File file, Resources res,
			String pkgname) {
    	
		InputStream dbInputStream = null;
		FileOutputStream fos = null;

		try {
			dbInputStream = res.openRawResource(R.raw.eplus_db);
			fos = new FileOutputStream(file);

			byte[] bytes = new byte[1024];
			int length;
			while ((length = dbInputStream.read(bytes)) > 0) {
				fos.write(bytes, 0, length);
			}
			fos.close();
			dbInputStream.close();
			
		} catch (FileNotFoundException e) {
		    LogTools.error(" 未找到文件 。",e); 
		} catch (IOException e) {
		    LogTools.error(" 文件IO异常 。",e); 
		}  
	} 
	
	public static void moveFile(InputStream from , File toFile) {
		 
		FileOutputStream fos = null;
		try {
			 fos  = new FileOutputStream(toFile);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		moveFile(from, fos);
	} 
	
	public static void moveFile(InputStream from , OutputStream to){
	
		try { 
			byte[] bytes = new byte[1024];
			int length;
			while ((length = from.read(bytes)) > 0) {
				to.write(bytes, 0, length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				from.close();
				to.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}